/**
 * Copyright 2018-2019 jianggujin (www.jianggujin.com).
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.jianggujin.modulelink.action.http;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.jianggujin.modulelink.action.JAbstractAction;
import com.jianggujin.modulelink.exception.JModuleLinkException;
import com.jianggujin.modulelink.util.JExceptionUtils;

/**
 * HTTP请求处理
 * 
 * @author jianggujin
 *
 */
public abstract class JGenericHttpAction extends JAbstractAction {

    @Override
    public Object execute(Object in) throws JModuleLinkException {
        JHttpHolder holder = (JHttpHolder) in;
        try {
            this.service(holder.getRequest(), holder.getResponse());
        } catch (Throwable e) {
            throw JExceptionUtils.handleException(e);
        } finally {
            this.executeComplete(holder);
        }
        return null;
    }

    /**
     * 请求处理
     * 
     * @param request  请求对象
     * @param response 响应对象
     * @throws IOException      IO异常
     * @throws ServletException Servlet异常
     */
    protected abstract void service(HttpServletRequest request, HttpServletResponse response)
            throws IOException, ServletException;

    /**
     * 执行完成的回调方法，用于清理资源
     * 
     * @param holder
     */
    protected void executeComplete(JHttpHolder holder) {
    }
}
